using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Abp.UI;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SOEI.Solution.Application.Contracts.DomainEntities.RegulatoryMange.Dtos;
using SOEI.Solution.DomainEntities.RegulatoryMange.DomainService;
using SOEI.Solution.DomainEntities.RegulatoryMange.Dtos;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using SOEI.Solution.Authorization;
using SOEI.Solution.DomainEntities.ContractManagement.DomainService;
using SOEI.Solution.DomainEntities.ContractManagement.Dtos;

using SOEI.Solution.DomainEntities.Parameters.DomainService;
using SOEI.Solution.Helper;
using System.Data;
using Abp.EntityFrameworkCore.Repositories;
using Microsoft.AspNetCore.SignalR;
using SOEI.Solution.SignaR;
using SOEI.Solution.Application.Contracts.Customized.RegulatoryMange;
using SOEI.Solution.Customized;
using ThirdParty.ESignClient;
using SOEI.Solution.ThirdParty.ESignClient.Models;
using SOEI.Solution.StructEntities.Contracts;
using SOEI.Solution.Integratedes.Organization;
using SOEI.Solution.Integratedes.Organization.DomainService;
using SOEI.Solution.CommonOthers.Pdf.DomainService;
using SOEI.Solution.CommonOthers.Pdf.StructEntities;
using SOEI.Solution.Integratedes.ElectronicSignet.DomainService;

namespace SOEI.Solution.DomainEntities.RegulatoryMange
{
	/// <summary>
	/// 【扩展模块】  <br/>
	/// 【功能描述】  ：XXX 模块<br/>
	/// 【创建日期】  ：2020.05.21 <br/>
	/// 【开发人员】  ：static残影<br/>
	///</summary>
	[ApiExplorerSettings(GroupName = "Manager", IgnoreApi = false)]
	public class AgreementAppService : SolutionAppServiceBase, IAgreementAppService
	{
		/// <summary>
		///【Agreement】仓储层
		/// </summary>
		private readonly IRepository<Agreement, string> _agreementRepository;

		/// <summary>
		///【Agreement】仓储层
		/// </summary>
		private readonly IRepository<AgreementBoth, string> _agreementBothRepository;

		/// <summary>
		///【Agreement】领域服务
		/// </summary>
		private readonly IAgreementManager _agreementManager;

		/// <summary>
		///【机构领域】 机构领域服务
		/// </summary>
		private readonly IOEconomyOrganiManager _oeconomyorganiManager;

		/// <summary>
		/// 电子签章接口
		/// </summary>
		private readonly IESignManager _eSignManager;

		/// <summary>
		/// PDF接口
		/// </summary>
		public IPdfManager _pdfManager;

		/// <summary>
		/// 合同处理接口
		/// </summary>
		public IContractManager _contractManager;

		/// <summary>
		/// 【电子签章】电子签章领域服务
		/// </summary>
		private readonly IOrgSignetManager _orgSignetManager;

		public AgreementAppService(
			IRepository<Agreement, string> agreementRepository,
			IAgreementManager agreementManager,
			IESignManager eSignManager,
			IRepository<AgreementBoth, string> agreementBothRepository,
			IOEconomyOrganiManager oeconomyorganiManager,
			IPdfManager pdfManager,
			IOrgSignetManager orgSignetManager,
			IContractManager contractManager
		)
		{
			_agreementRepository = agreementRepository;
			_agreementManager = agreementManager;
			_eSignManager = eSignManager;
			_agreementBothRepository = agreementBothRepository;
			_oeconomyorganiManager = oeconomyorganiManager;
			_pdfManager = pdfManager;
			_orgSignetManager = orgSignetManager;
			_contractManager = contractManager;
		}

		#region -------------------------------------------------辅助工具生成---------------------------------------------- 

		/// <summary>
		///【Agreement】获取的分页列表信息
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize]
		public async Task<PagedResultDto<AgreementViewListDto>> GetPaged(GetAgreementsInput input)
		{
			var result = _agreementManager.QueryEntityListAsNoTracking();

			//// TODO:根据传入的参数添加过滤条件
			var query = result.Where(a => a.JGLXDM != "03")
						.WhereIf(!input.state.IsNullOrWhiteSpace(), a => input.state.Contains(a.JGXYZTDM))
						.WhereIf
						(
							!input.FilterText.IsNullOrWhiteSpace(),
							a => a.CMR.Contains(input.FilterText)
							  || a.MSR.Contains(input.FilterText)
							  || a.CMRZJHM.Contains(input.FilterText)
							  || a.CMRLXDH.Contains(input.FilterText)
							  || a.MSRZJHM.Contains(input.FilterText)
							  || a.MSRLXDH.Contains(input.FilterText)
							  || a.JGXYH == input.FilterText
							  || a.HTDJHID == input.FilterText
						)
						.WhereIf(input.StartDate.HasValue, a => a.LRSJ >= input.StartDate)
						.WhereIf(input.EndDate.HasValue, a => a.LRSJ < input.EndDate.Value.AddDays(1));

			var count = await query.CountAsync();

			var entityList = await query
					.OrderBy(input.Sorting).AsNoTracking()
					.PageBy(input)
					.ToListAsync();

			var entityListDtos = ObjectMapper.Map<List<AgreementViewListDto>>(entityList);

			return new PagedResultDto<AgreementViewListDto>(count, entityListDtos);
		}


		/// <summary>
		///【Agreement】通过指定id获取MemberListDto信息
		/// </summary>
		[AbpAuthorize]
		public async Task<AgreementListDto> GetById(EntityDto<string> input)
		{
			var entity = await _agreementRepository.GetAsync(input.Id);

			var dto = ObjectMapper.Map<AgreementListDto>(entity);
			return dto;
		}

		/// <summary>
		///【Company】 获取编辑
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize]
		public async Task<GetAgreementForEditOutput> GetForEdit(EntityDto<string> input)
		{
			var output = new GetAgreementForEditOutput();
			AgreementViewDto editDto;

			if (!string.IsNullOrEmpty(input.Id))
			{
				var entity = await _agreementManager.GetForEditAsync(input.Id);
				editDto = ObjectMapper.Map<AgreementViewDto>(entity);
			}
			else
			{
				editDto = new AgreementViewDto();
			}
			output.Agreement = editDto;

			return output;
		}
		/// <summary>
		///【Agreement】 添加或者修改的公共方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize]
		public async Task<AgreementEditDto> CreateOrUpdate(CreateOrUpdateAgreementInput input)
		{
			if (!string.IsNullOrEmpty(input.Agreement.Id))
			{
				return await Update(input.Agreement);
			}
			else
			{
				return await Create(input.Agreement);
			}
		}

		/// <summary>保存协议的变更信息
		/// </summary>
		/// <param name="entity"></param>
		/// <returns></returns>
		protected async Task<AgreementChange> SaveAgreementChange(Agreement entity)
		{
			return await _agreementManager.SaveAgreementChange(new AgreementChange()
			{
				Id = _agreementManager.GetAgreementChangeId(),
				HTDJH = entity.HTDJH,
				ZLSZQ = entity.ZLSZQ,
				JGJE = entity.JGJE,
				YCXFKQX = entity.YCXFKQX,
				YCXFKJE = entity.YCXFKJE,
				AJFKQX = entity.AJFKQX,
				AJSFJE = entity.AJSFJE,
				JFJSZHKHYH = entity.JFJSZHKHYH,
				JFJSZHMC = entity.JFJSZHMC,
				JFJSZHZH = entity.JFJSZHZH,
				JFZJHM = entity.JFZJHM,
				YFJSZHKHYH = entity.YFJSZHKHYH,
				YFJSZHMC = entity.YFJSZHMC,
				YFJSZHZH = entity.YFJSZHZH,
				YFDLRZJHM = entity.YFZJHM,
				QTSX = entity.QTSX,
				LRSJ = _agreementManager.FindSysDate(),
				LRRBH = entity.LRRBH,
				LRRXM = entity.LRRXM,
				AJBLZT = "10",
				JGXYBH = entity.Id,
				JGBH = entity.JGBH,
				JGLXDM = entity.JGLXDM,
				JGXYZTDM = entity.JGXYZTDM,
				JGZHDM = entity.JGZHDM,
				JFZHJSFS = entity.JFJSZHFS,
				YFZHJSFS = entity.YFJSZHFS,
				YFDKYH = entity.YFDKYH,
				YXRQ = entity.YXRQ,
				BGZT = "00",
				JGXX = entity.JGXYH,
				QDM = entity.QDM,
				QYDM = entity.QYDM,
				QYMC = entity.QYMC,
				FWZLXX = entity.FWZLXX,
				CQZH = entity.CQZH,
				JZMJ = entity.JZMJ,
				GHYT = entity.GHYT,
				FWZJ = entity.FWZJ,
				HTQDRQ = entity.HTQDRQ,
				HTDJHID = entity.HTDJHID,
				SFXMS = entity.SFXMS
			});
		}

		/// <summary>
		///【Agreement】新增
		/// </summary>
		[AbpAuthorize]
		protected virtual async Task<AgreementEditDto> Create(AgreementEditDto input)
		{
			//TODO:新增前的逻辑判断，是否允许新增

			if (string.IsNullOrWhiteSpace(input.HTDJH))
			{
				throw new UserFriendlyException("合同编号不能为空！");
			}

			var query = _agreementManager.QueryContractBoth();

			var vBothList = await query.Where(a => a.HTDJH == input.HTDJH).ToListAsync();

			if (vBothList == null || vBothList.Count < 1)
			{
				throw new UserFriendlyException("合同双方信息不完整！");
			}

			var vJGXYBH = _agreementManager.GetAgreementId();

			var vJGXYH = await _agreementManager.GetAgreementRegId();

			string vCMR = "";
			string vCMRZJHM = "";
			string vCMRLXDH = "";
			string vMSR = "";
			string vMSRZJHM = "";
			string vMSRLXDH = "";

			#region 保存协议双方

			foreach (var item in vBothList)
			{
				
				if(item.SFLBDM == "01")
				{
					vCMR += item.XM + ",";
					vCMRZJHM += item.ZJHM + ",";
					vCMRLXDH += item.LXDH + ",";
				}
				else if(item.SFLBDM == "02")
				{
					vMSR += item.XM + ",";
					vMSRZJHM += item.ZJHM + ",";
					vMSRLXDH += item.LXDH + ",";
				}

				await _agreementManager.CreateAsyncAgreementBoth(new AgreementBoth()
				{
					Id = _agreementManager.GetAgreementBothId(),
					XM = item.XM,
					ZJLX = item.ZJLX,
					ZJHM = item.ZJHM,
					LXDH = item.LXDH,
					TXDZ = item.TXDZ,
					SFLBDM = item.SFLBDM,
					JGXYBH = vJGXYBH,
					ZJLXDM = item.ZJLXDM
				});
			}

			#endregion

			var entity = ObjectMapper.Map<Agreement>(input);

			entity.Id = vJGXYBH;
			entity.JGXYH = vJGXYH;

			var contract = await _agreementManager.FindContractAsync(a => a.Id == input.HTDJH);

			if (contract == null)
			{
				throw new UserFriendlyException("合同信息不完整！");
			}

			entity.FWZLXX = string.IsNullOrWhiteSpace(contract.LocatedInformation) ? "无" : contract.LocatedInformation;
			entity.CQZH = contract.CertificateName_2;
			entity.LRSJ = _agreementManager.FindSysDate();
			entity.JZMJ = contract.BuildingArea;
			entity.GHYT = contract.HouseUsageParam.Value;
			entity.FWZJ = contract.HousePrice;
			entity.HTQDRQ = contract.VerifyTime.HasValue ? contract.VerifyTime.Value.ToString("yyyy-MM-dd") : null;
			entity.HTDJHID = contract.ContractRegistrationId;
			entity.ZLSZQ = contract.PropertyCard.Located.QMC;
			entity.SFXMS = "1";
			entity.ISJJJGTJ = "0";

			entity.CMR = vCMR.TrimEnd(',');
			entity.CMRZJHM = vCMRZJHM.TrimEnd(',');
			entity.CMRLXDH = vCMRLXDH.TrimEnd(',');

			entity.MSR = vMSR.TrimEnd(',');
			entity.MSRZJHM = vMSRZJHM.TrimEnd(',');
			entity.MSRLXDH = vMSRLXDH.TrimEnd(',');

			entity.AJBLZT = "10";

			if (input.payType == "1")
			{
				entity.JGLXDM = "01";
			}
			else
			{
				entity.JGLXDM = "02";
			}

			entity.JGXYZTDM = "00";
			entity.QDM = contract.PropertyCard.Located.QDM;
			entity.QYDM = contract.PropertyCard.QYDM;
			entity.QYMC = contract.PropertyCard.QMC;

			//调用领域服务
			entity = await _agreementManager.CreateAsync(entity);

			if (entity.JGLXDM != "03")
			{
				await SaveAgreementChange(entity);
			}

			var dto = ObjectMapper.Map<AgreementEditDto>(entity);

			return dto;
		}

		/// <summary>
		///【Agreement】编辑
		/// </summary>
		[AbpAuthorize]
		protected virtual async Task<AgreementEditDto> Update(AgreementEditDto input)
		{
			//TODO:更新前的逻辑判断，是否允许更新
			var key = input.Id;

			var entity = await _agreementRepository.GetAsync(key);

			ObjectMapper.Map(input, entity);

			if (input.payType == "1")
			{
				entity.JGLXDM = "01";
			}
			else
			{
				entity.JGLXDM = "02";
			}

			entity.LRSJ = _agreementManager.FindSysDate();

			entity.PDFGX = "1";

			await _agreementManager.UpdateAsync(entity);

			if (entity.JGLXDM != "03")
			{
				await SaveAgreementChange(entity);
			}

			var dto = ObjectMapper.Map<AgreementEditDto>(entity);
			return dto;
		}

		/// <summary>
		///【Agreement】删除信息
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize]
		[HttpPost]
		public async Task Delete(EntityDto<string> input)
		{
			await CheckCanDelAgreement(input.Id);

			
			await _agreementManager.DeleteAsync(input.Id);
		}

	 
		/// <summary>
		///【Agreement】 批量删除Member的方法
		/// </summary>
		[AbpAuthorize]
		public async Task BatchDelete(List<string> input)
		{
		
			await _agreementManager.BatchDelete(input);
		}

		#endregion

		#region -------------------------------------------------用户自定义------------------------------------------------
		/*请在此扩展应用服务实现*/

		/// <summary>获取监管账号信息
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize]
		public async Task<ICollection<RegulatoryAccountViewDto>> GetBankList(GetSuperviseBanksInput input)
		{
			var regulator = await _agreementManager.QueryAllRegulator().FirstOrDefaultAsync();

			var query = _agreementManager.QueryAllRegulatoryAccount()
				.WhereIf(regulator != null, a => a.JGBH == regulator.Id)
				.Select(a => new RegulatoryAccount()
				{
					Id = a.Id,
					JGBH = a.JGBH,
					JGZH = a.JGZH,
					superviseBank = a.superviseBank
				});

			var entityList = await query
					.OrderBy(input.Sorting)
					.ToListAsync();

			var entityListDtos = ObjectMapper.Map<ICollection<RegulatoryAccountViewDto>>(entityList);

			return entityListDtos;
		}

		/// <summary>验证是否可以删除监管协议
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		protected async Task CheckCanDelAgreement(string id)
		{
			if (string.IsNullOrWhiteSpace(id))
			{
				throw new UserFriendlyException("监管协议编号不能为空！");
			}

			if(await _agreementRepository.GetAll().AsNoTracking()
				.AnyAsync(a=> a.Id == id && a.JGXYZTDM != "00"))
			{
				throw new UserFriendlyException("该监管协议状态已经发生变化！");
			}
		}

		/// <summary>验证该合同登记号是否可以签订监管协议
		/// </summary>
		[AbpAuthorize]
		protected async Task CheckCanSignAgreement(string pContractNum, string pAgreementId)
		{

			var contract = await _agreementManager.FindContractAsync(a => a.ContractRegistrationId == pContractNum);

			if (contract == null)
			{
				throw new UserFriendlyException("合同登记号不存在对应合同！");
			}

			string vTips = string.Format("合同登记号为【{0}】的合同", pContractNum);

			switch (contract.ContractHandlingStatusCode)
			{
				case "10":
					throw new UserFriendlyException(vTips + "正在登记中！");
				case "14":
					throw new UserFriendlyException(vTips + "正在注销中！");
				case "15":
					throw new UserFriendlyException(vTips + "正在变更中！");
			}

			//验证是否签订了监管协议
			if (await _agreementManager.IsExistTreatyAgreement(contract.Id, pAgreementId))
			{
				throw new UserFriendlyException(vTips + "已签订监管协议信息！");
			}
			else if (await _agreementManager.IsExistNoTreatyAgreement(contract.Id, pAgreementId))
			{
				throw new UserFriendlyException(vTips + "已签订非监管协议信息！");
			}

		}

		/// <summary>查询可以签订协议的合同
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize]
		public async Task<GetCanSignAgreementContractOutput> SelCanSignAgreementContract(GetCanSignAgreementContractInput input)
		{
			if (string.IsNullOrWhiteSpace(input.contractNum))
			{
				throw new UserFriendlyException("合同登记号不能为空！");
			}

			input.contractNum = input.contractNum.ToUpper();

			await CheckCanSignAgreement(input.contractNum, input.Id);

			var output = new GetCanSignAgreementContractOutput();

			var entity = await _agreementManager.FindContractAsync(
				a => a.ContractStatusId == "09"
				  && a.ContractHandlingStatusCode == "11"
				  && a.ContractRegistrationId == input.contractNum);

			output.contract = ObjectMapper.Map<ContractViewWithAgreementDto>(entity); ;

			return output;
		}

		[AbpAuthorize]
		public async Task<PagedResultDto<AgreementViewListDto>> GetProvePaged(GetAgreementsInput input)
		{
			var result = _agreementManager.QueryEntityListAsNoTracking();

			// TODO:根据传入的参数添加过滤条件
			var query = result
						.Where(a=> a.JGZMCJBZ == "1")
						.WhereIf
						(
							!input.FilterText.IsNullOrWhiteSpace(),
							a => a.CMR.Contains(input.FilterText)
							  || a.MSR.Contains(input.FilterText)
							  || a.CMRZJHM.Contains(input.FilterText)
							  || a.CMRLXDH.Contains(input.FilterText)
							  || a.MSRZJHM.Contains(input.FilterText)
							  || a.MSRLXDH.Contains(input.FilterText)
							  || a.JGXYH == input.FilterText
							  || a.HTDJHID == input.FilterText
						)
						.WhereIf(input.StartDate.HasValue, a => a.YXRQ >= input.StartDate)
						.WhereIf(input.EndDate.HasValue, a=> a.YXRQ < input.EndDate.Value.AddDays(1));


			var count = await query.CountAsync();

			var entityList = await query
					.OrderBy(input.Sorting).AsNoTracking()
					.PageBy(input)
					.ToListAsync();

			var entityListDtos = ObjectMapper.Map<List<AgreementViewListDto>>(entityList);

			return new PagedResultDto<AgreementViewListDto>(count, entityListDtos);
		}

		/// <summary>验证是否可以提交监管协议
		/// </summary>
		protected async Task CheckCanSubmitAgreement(string pId)
		{
			if (string.IsNullOrWhiteSpace(pId))
			{
				throw new UserFriendlyException("监管协议编号不能为空！");
			}

			var agreement = await _agreementManager.FindByIdAsync(pId);

			if(agreement == null)
			{
				throw new UserFriendlyException("监管协议编号不存在对应协议！");
			}

			if(agreement.JGXYZTDM != "00")
			{
				throw new UserFriendlyException("该监管协议状态已经发生变化！");
			}

			if (await _agreementRepository.GetAll().AsNoTracking()
				.AnyAsync(
					a => "00,01".IndexOf(a.JGXYZTDM) != -1
					  && a.HTDJH == agreement.HTDJH 
					  && a.Id != agreement.Id)
				)
			{
				throw new UserFriendlyException("该合同已存在有效监管协议，不可再次签订！");
			}

		}

		/// <summary>提交监管协议至管理端
		/// </summary>
		[AbpAuthorize]
		public async Task SubmitAgreement(EntityDto<string> input)
		{
			await CheckCanSubmitAgreement(input.Id);

			await _agreementManager.SubmitAgreement(input.Id);
		}

		/// <summary>监管协议信息变更
		/// </summary>
		[AbpAuthorize]
		public async Task<AgreementChangeEditDto> CreateOrUpdateAgreementChange(AgreementChangeInput input)
		{
			var dto = input.AgreementChange;

			if (string.IsNullOrWhiteSpace(dto.Id))
			{
				await CheckCanChangeAgreement(dto);

				return await CreateAgreementChange(dto);
			}
			else
			{
				return await UpdateAgreementChange(dto);
			}

		}

		protected async Task CheckCanChangeAgreement(AgreementChangeEditDto input)
		{
			if (!await _agreementManager.CheckAgreementAny(
				a => a.JGXYZTDM == "01"
				  && "10,03,01,04".IndexOf(a.AJBLZT) != -1
				  && a.JGLXDM != "03"
				  && a.JGXYH == input.JGXYH))
			{
				throw new UserFriendlyException("您要变更的监管协议不存在！");
			}

			if (await _agreementManager.CheckAgreementAny(
				a => a.JGXYZTDM == "01"
				  && a.AJBLZT == "04"
				  && a.JGLXDM != "03"
				  && a.JGXYH == input.JGXYH))
			{
				throw new UserFriendlyException("此监管协议正在变更中，不能再次变更！");
			}
		}

		protected async Task<AgreementChangeEditDto> CreateAgreementChange(AgreementChangeEditDto input)
		{
			var entity = ObjectMapper.Map<AgreementChange>(input);

			var agreement = await _agreementRepository.GetAsync(entity.JGXYBH);

			entity.Id = _agreementManager.GetAgreementChangeId();
			entity.HTDJH = agreement.HTDJH;
			entity.ZLSZQ = agreement.ZLSZQ;
			entity.AJBLZT = "04";
			entity.JGBH = agreement.JGBH;
			entity.JGXYZTDM = agreement.JGXYZTDM;
			entity.BGZT = "00";
			entity.JGXX = agreement.JGXYH;
			entity.QDM = agreement.QDM;
			entity.QYDM = agreement.QYDM;
			entity.QYMC = agreement.QYMC;
			entity.FWZLXX = agreement.FWZLXX;
			entity.CQZH = agreement.CQZH;
			entity.JZMJ = agreement.JZMJ;
			entity.GHYT = agreement.GHYT;
			entity.FWZJ = agreement.FWZJ;
			entity.HTQDRQ = agreement.HTQDRQ;
			entity.HTDJHID = agreement.HTDJHID;
			entity.JGZMCJBZ = agreement.JGZMCJBZ;
			entity.LRSJ = _agreementManager.FindSysDate();
			entity.SFXMS = "1";
			entity.SFTJ = "0";

			await _agreementManager.SaveAgreementChange(entity);

			agreement.AJBLZT = "04";

			await _agreementRepository.UpdateAsync(agreement);

			return ObjectMapper.Map<AgreementChangeEditDto>(entity);
		}

		protected async Task<AgreementChangeEditDto> UpdateAgreementChange(AgreementChangeEditDto input)
		{
			var key = input.Id;

			var entity = await _agreementManager.GetAgreementChangeAsync(key);

			input.JGXYBH = entity.JGXYBH;
			input.FWZJ = entity.FWZJ;
			input.SFTJ = entity.SFTJ;
			input.PDFID = entity.PDFID;
			input.PDFGX = "1";
			
			ObjectMapper.Map(input, entity);

			await _agreementManager.UpdateAgreementChange(entity);

			return ObjectMapper.Map<AgreementChangeEditDto>(entity);
		}

		/// <summary>通过监管协议编号获取优先变更中的监管协议信息
		/// </summary>
		public async Task<GetAgreementForEditOutput> GetForChangeEdit(EntityDto<string> input)
		{
			var dto = await GetForEdit(input);

			if(dto != null)
			{
				var entity = await _agreementManager.FindAgreementChangeAsync(a => a.AJBLZT == "04" && a.JGXYBH == input.Id);

				if(entity != null)
				{
					dto.AgreementChange = ObjectMapper.Map<AgreementChangeEditDto>(entity);
				}
			}

			return dto;
		}

		/// <summary>检查是否可以提交监管协议变更信息
		/// </summary>
		protected async Task CheckCanSubmitAgreementChange(string id)
		{
			if(!await _agreementManager.CheckAgreementChangeAny(a => a.AJBLZT == "04" && a.SFTJ != "1" && a.Id == id))
			{
				throw new UserFriendlyException("该监管协议变更信息状态已经发生变化！");
			}
		}

		/// <summary>提交监管协议变更
		/// </summary>
		public async Task SubmitAgreementChange(EntityDto<string> input)
		{
			await CheckCanSubmitAgreementChange(input.Id);


			await _agreementManager.SubmitAgreementChange(input.Id);
		}

		/// <summary>测试调用存储过程
		/// </summary>
		/// <returns></returns>
		public async Task<string> FindWaterCode()
		{

			var vParam = ParamCollect.FromObj(new
			{
				IS_JGXYBH = "0000000359",
				IS_LRR = "SYS",
				IS_LRRXM = "管理员",
				IS_SFBG = "0"
			}, ParameterDirection.Input);

			vParam.Add("IS_SYBH", ParameterDirection.Output);

			await _agreementRepository.GetDbContext().Database.ExecuteStoreProcedure("PKG_CLFZJJGXX.SP_GET_SYBH", vParam);

			return vParam.GetDynamic().IS_SYBH;
		}

		public async Task<DataSet> FindJGYHList()
		{
			var vParam = ParamCollect.FromObj(new {
				IS_JGJGBH = string.Empty
			});

			vParam.AddFromObj(new {
				OS_RETURN = 0,
				OS_ERRORINF = string.Empty
			}, ParameterDirection.Output);

			return await _agreementRepository.GetDbContext().Database.ExecuteStoreProcedure("PKG_CLFZJJGXX.SP_GET_JGYHLIST", vParam, "CURSOR");
		}

		/// <summary>
		/// 【Edit By hua】 根据 JGXYBH 获取所有签署对象 
		/// </summary>
		/// <returns></returns>
		public async Task<ICollection<AgreementBoth>> GetAgreementBothsFromID(EntityDto<string> input)
		{
			if (string.IsNullOrEmpty(input.Id)) {
				throw new UserFriendlyException("协议编号不能为空！");
			}

			var entityList = await this._agreementManager.QueryAgreementBoth()
						.AsNoTracking()
						.Where(x => x.JGXYBH == input.Id)
						.OrderBy(x => x.SFLBDM)
						.ToListAsync();
		
			return entityList;
		}

		/// <summary>
		/// 【Edit By hua 测试用】 发起邀请通知(已经发送过的就不在发送了)
		/// </summary>
		/// <returns></returns>
		public async Task SendAllForBothsNotify(BothsNotifyInput input) 
		{
			var entityList = await this._agreementManager.QueryAgreementBoth()
						.AsNoTracking()
						.Where(x => x.JGXYBH == input.Id)
						.Where(x=>x.SignetStatus == ESignetStatus.Default) // 获取没有完成的
						.Where(x=>x.SFLBDM != "01")
						.OrderBy(x => x.SFLBDM)
						.ToListAsync();

			var contractEntity = new ContractEntity();

			foreach (var item in entityList) {

				await this.CreateAndInvitations(item);

				var invEntity = new InvitationEntity()
				{
					BizId = string.Format("{0},{1}", input.ConnectionId,item.Id),
					IdNumber = item.ZJHM,
					Mobile  = item.LXDH,
					Name = item.XM,
					InviteeOid = item.AccountID
				};
				// 发送请求
				await _eSignManager.InvitationsAsync(invEntity);
				// 创建合同并且发布
			}
		}

		/// <summary>
		/// 发送合同信息 
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task SendContractForBothsNotify(BothsNotifyInput input)
		{
			//1. 收集当前登录用户信息和企业信息当前企业为发起人
			var userEntity = await this.GetPersonChecker();
			//2. 当前登录的机构信息
			var organiEntity = await this._oeconomyorganiManager.FindByIdAsync(userEntity.OriginalNumber);
			//3. 判断是否有权进行合同发起
			var orgSignEntity =  await _orgSignetManager.FindByPersonIDAsync(organiEntity.GLYBH);
			//4. 获取合同文件内容
			var pdfParam = new PdfParam() {
				 Id = input.PdfId
			};
			var PdfBuffer = await this._pdfManager.GetPdfAsync(pdfParam);
			//5. 获取合同签署相关方集合
			var entityList = await this._agreementManager.QueryAgreementBoth()
						.AsNoTracking()
						.Where(x => x.JGXYBH == input.Id)
						.Where(x => x.SignetStatus == ESignetStatus.Default) // 获取没有完成的
						.Where(x => x.SFLBDM != "01")
						.OrderBy(x => x.SFLBDM)
						.ToListAsync();
			//6.创建合同数据准备
			var contractEntity = new ContractEntity();
			contractEntity.AliasName = "二手房资金监管协议";
			contractEntity.FileName = "二手房资金监管协议.pdf"; // 必须是PDF文件
			contractEntity.FileBuffer = PdfBuffer;  // 文件二进制数据
			contractEntity.Flow.AccountId = orgSignEntity.AccountID;  // 流程发起人为 当前登录的所属机构用户（其实应该是资金监管机构）
			contractEntity.Flow.businessScene = "资金监管合同";
			contractEntity.Flow.OrganiAccountID = orgSignEntity.ORGID; // 发起方所属机构的账号

			foreach (var item in entityList) {

				await this.CreateAndInvitations(item);
				// 配置签署相关方
				contractEntity.Manuals.Add(new ManualEntity { AccountID = item.AccountID, PosPage= 1, PosX="500", PosY="500" });
			}
			// 发起合同

			await this._contractManager.CreateRegulatorContract(contractEntity);
		}

		#endregion


		#region -------------------------------------------------用户自定义------------------------------------------------

		/// <summary>
		/// 【 Edit by Hua 】创建和发送邀请通知
		/// </summary>
		/// <returns></returns>
		protected async Task CreateAndInvitations(AgreementBoth item) 
		{
			// 如果已经存在账号编号就不需要创建了
			if (!string.IsNullOrEmpty(item.AccountID)) {
				return;
			}

			// 创建第三方账号
			var AccountResult = await _eSignManager.CreateAccountAsync(new AccountEntity
			{
				ThirdPartyUserId = item.LXDH,
				Mobile = item.LXDH,
				IdNumber = item.ZJHM,
				Name = item.XM
			});
			item.AccountID = AccountResult.Data.AccountID;
			await this._agreementBothRepository.UpdateAsync(item);
		}

		#endregion
	}
}
